//
//  JDHomeTypeFakeView.swift
//  DragonWallet
//
//  Created by volantPig on 2025/10/15.
//

import UIKit

class JDHomeTypeFakeView: UIView {
    
    var changeClassificationCallBack:((Int,JDGoodsTypeModel?)->())?
    
    var gotoClassificationDetailCallBack:(()->())?
    
    var selectedIndex = 0
    
    var typeModels: [JDGoodsTypeModel?]? {
        didSet {
            self.typeCollectionView.reloadData()
            self.moveView.pageNumber =  Int(ceil(CGFloat(self.typeModels?.count ?? 0)/5.0))
        }
    }
    
    lazy var typeCollectionView: UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.scrollDirection = .horizontal
        
        let collectionView = UICollectionView(frame: .zero, collectionViewLayout: layout)
        collectionView.isPagingEnabled = true
        collectionView.delegate = self
        collectionView.dataSource = self
        collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: "myCell")
        collectionView.showsHorizontalScrollIndicator = false
        return collectionView
    }()
    
    lazy var bottomView: UIView = {
        var bottom = UIView()
        return bottom
    }()
    
    lazy var moveView: JDTypeLineView = {
        let move = JDTypeLineView()
        return move
    }()
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        self.backgroundColor = .white
        self.setupUIElements()
    }
    
    func setupUIElements() {
        self.addSubview(self.typeCollectionView)
        self.typeCollectionView.snp.makeConstraints { make in
//            make.leading.trailing.top.equalTo(self)
            make.leading.equalTo(self).offset(12)
            make.trailing.equalTo(self).offset(-12)
            make.top.equalTo(self)
            make.height.equalTo(91)
        }
        
        self.addSubview(self.bottomView)
        self.bottomView.snp.makeConstraints { make in
            make.leading.trailing.equalTo(self)
            make.top.equalTo(self.typeCollectionView.snp.bottom)
            make.bottom.equalTo(self)
        }
        
        self.bottomView.addSubview(self.moveView)
        self.moveView.snp.makeConstraints { make in
            make.centerX.centerY.equalTo(self.bottomView)
            make.size.equalTo(CGSizeMake(33, 4))
        }
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}

extension JDHomeTypeFakeView: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.typeModels?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "myCell", for: indexPath)
        
        for subV in cell.contentView.subviews {
            subV.removeFromSuperview()
        }
        
        let currentModel = self.typeModels?[indexPath.row]
        
        let bgView = UIView()
        cell.contentView.addSubview(bgView)
        bgView.snp.makeConstraints { make in
            make.leading.equalTo(cell.contentView).offset(0.5)//.offset(5)
            make.trailing.equalTo(cell.contentView).offset(-0.5)//.offset(-5)
            make.top.equalTo(cell.contentView).offset(8)
            make.bottom.equalTo(cell.contentView).offset(-0.5)
        }
        
        let typeImageV = UIImageView()
        bgView.addSubview(typeImageV)
        typeImageV.snp.makeConstraints { make in
            make.centerX.equalTo(bgView)
            make.top.equalTo(bgView).offset(4)
            make.size.equalTo(CGSizeMake(52, 52))
        }
        if currentModel?.name == "全部" || currentModel?.name == "分类"  {
            typeImageV.image = UIImage(named: currentModel?.logo ?? "")
        } else {
            typeImageV.downloadImage(currentModel?.logo ?? "")
        }
        
        let typeNameLabel = UILabel()
        bgView.addSubview(typeNameLabel)
        typeNameLabel.snp.makeConstraints { make in
            make.centerX.equalTo(bgView)
            make.top.equalTo(typeImageV.snp.bottom).offset(4)
            make.height.equalTo(18)
        }
        typeNameLabel.text = currentModel?.name//"休闲食品"
        
        
        if indexPath.row == self.selectedIndex {
            bgView.makeCorner(8)
            bgView.makeBorder(color("#FF5027"), 0.5)
            bgView.backgroundColor = color("#FF5027").withAlphaComponent(0.03)
            
            typeNameLabel.labelConfig(textAlignment: .center, font: UIFont.systemFont(ofSize: 13, weight: .semibold), textColor: color("#FF5027"), numberOfLines: 1)
        } else {
            bgView.makeCorner(8)
            bgView.makeBorder(.white, 0.5)
            bgView.backgroundColor = .white
            
            typeNameLabel.labelConfig(textAlignment: .center, font: UIFont.systemFont(ofSize: 13, weight: .regular), textColor: color("#FF5027"), numberOfLines: 1)
        }
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSizeMake(floor((screenWidth-24.0)/5.0), 90)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0.001
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        print("单行点击:\(indexPath.row),应该触发回调的，同步外部数据")
        if self.selectedIndex == indexPath.row {
            // 点击的相同，那么，无操作
        } else {
            if ((self.typeModels?.count ?? 1) - 1) == indexPath.row {
                self.gotoClassificationDetailCallBack?()
            } else {
                self.selectedIndex = indexPath.row
                self.typeCollectionView.reloadData()
                let currentModel = self.typeModels?[indexPath.row]
                self.changeClassificationCallBack?(self.selectedIndex,currentModel)
            }
            
        }
        
    }
    
}

extension JDHomeTypeFakeView: UIScrollViewDelegate {
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        // 水平滚动计算当前页
        let currentPage = ceil(scrollView.contentOffset.x / scrollView.frame.width)
        print("当前页码: \(currentPage)")
        
        self.moveView.moveLineAction(CGFloat(currentPage))
        
        // 更新你的页面指示器或其他UI，例如 pageControl.currentPage = currentPage
    }
}
